<?php
/*******************************************************************************

    FinalsClub.org is a platform for students and faculty to collaborate
    and share their knowledge with the world.

    Copyright (C) 2009  Andrew Magliozzi

    This file is a part of FinalsClub.org.

    FinalsClub.org is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    To contact FinalsClub.org, send an email to info@finalsclub.org, or
    send mail to Finals Club, c/o Veritas Tutors, 1132 Massachusetts Avenue,
    Cambridge, MA 02138.

*******************************************************************************/

/**
 * messages actions.
 *
 * @package    FinalsClub
 * @subpackage messages
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 12474 2008-10-31 10:41:27Z fabien $
 */
class messagesActions extends sfActions {
	
	public function preExecute() {
		$request = $this->getRequest();
		$this->group_id = $request->getParameter('group_id');
		$this->group = GroupPeer::retrieveById($this->group_id);
	
	}
	
	public function executeIndex(sfWebRequest $request) {
		$page = $request->getParameter('page', 1);
		$this->folder = $request->getParameter('folder', MessagePeer::INBOX_FOLDER);
		$this->message_pager = MessagePeer::retrieveByGroupIdPager($this->group_id, $this->getUser()->getId(), 
			$this->folder, $page, 30);
	}

	public function executeNew(sfWebRequest $request) {
		$this->form = new MessageForm();
	}

	public function executeCreate(sfWebRequest $request) {
		$this->forward404Unless($request->isMethod('post'));
		$this->form = new MessageForm();
		$messageRequest = $request->getParameter($this->form->getName());
		$messageRequest['user_id'] = $this->getUser()->getId();
		$messageRequest['sender_id'] = $this->getUser()->getId();
		$messageRequest['type'] = 'group';
		$messageRequest['type_id'] = $this->group_id;
		$messageRequest['folder']  = MessagePeer::SENT_FOLDER;
		$messageRequest['recipient_id'] = null;
		$messageRequest['seen'] = true;

		$reply_id = $request->getParameter('reply_id');
		// retrieve the origin id of the message
		if($reply_id && $originMessage = MessagePeer::retrieveById($reply_id)) {
			if($originMessage->getOriginId() != null) {
				// persist the original id of the first message
				$messageRequest['origin_id'] = $originMessage->getOriginId();
			} else {
				// this is the first reply in this conversation thread
				$messageRequest['origin_id'] = $reply_id;
			}
			// persist the conversation message history
			$messageRequest['message_history_id'] = $originMessage->getMessageHistoryId();
		} else {
			// create a new history for this message
			$messageHistory = new MessageHistory();
			$messageHistory->setUserId($this->getUser()->getId());
			$messageHistory->save();
			$messageRequest['message_history_id'] = $messageHistory->getId();
		}
		
		$request->setParameter($this->form->getName(), $messageRequest);
		// save the message
		$this->form->bind($messageRequest);
		if($this->form->isValid()) {
			$message = $this->form->save();
			
			// retrieve all group members
			$groupMembers = GroupMemberPeer::retrieveByGroupId($this->group_id, GroupMemberPeer::APPROVED_STATUS);
			
			// send the message to all group members
			foreach($groupMembers as $groupMember) {
				$messageForm = new MessageForm();
				$messageRequest = $request->getParameter($messageForm->getName());
				if($groupMember->getUserId() != $this->getUser()->getId()) {	// make sure it's not sent again to the user that has sent it
					$messageRequest['folder'] = MessagePeer::INBOX_FOLDER;
					$messageRequest['recipient_id'] = $groupMember->getUserId();
					$messageRequest['user_id'] = $groupMember->getUserId();
					$messageRequest['seen'] = false;
					
					if($request->getParameter('reply_id')) {
						$messageRequest['replied'] = true;
					}
										
					$messageForm->bind($messageRequest);
					if($messageForm->isValid()) {
						$messageForm->save();
					}
					$this->form = $messageForm;
				}				
			}
			$this->getUser()->setFlash('success', 'Your message has been successfully sent');
		}		
		
		
		$this->forward('messages', 'index');
		// $this->redirect('messages/index?group_id='.$this->group_id.'&folder='.MessagePeer::SENT_FOLDER);
	}
	
	public function executeUpdate(sfWebRequest $request) {
		$this->forward404Unless($request->isMethod('post'));
		$message_ids = $request->getParameter('messages');
		if($message_ids) {
			$c = new Criteria();
			$c->add(MessagePeer::USER_ID, $this->getUser()->getId());
			$c->add(MessagePeer::ID, $message_ids, Criteria::IN);
			$updateCriteria = new Criteria();
			$updateCriteria->add(MessagePeer::SEEN, $request->getParameter('seen', false));
			BasePeer::doUpdate($c, $updateCriteria, Propel::getConnection());
			$this->getUser()->setFlash('success', 'Your messages have been updated');
		} else {
			$message = MessagePeer::retrieveById($request->getParameter('id'));
			if($message && $message->getUserId() == $this->getUser()->getId()) {
				$message->setSeen($request->getParameter('seen'), false);
				$message->save();
				$this->getUser()->setFlash('success', 'Your message has been updated');
			} else {
				$this->getUser()->setFlash('error', 'Could not update message');
			}
		}

		$this->redirect('messages/index?group_id='.$this->group_id.'&folder='.$request->getParameter('folder', MessagePeer::INBOX_FOLDER));
		//$this->forward('messages', 'index');
	}
	
	public function executeDelete(sfWebRequest $request) {
		$request->checkCSRFProtection();
		
		$message_ids = $request->getParameter('messages');
		if($message_ids) {
			$c = new Criteria();
			$c->add(MessagePeer::USER_ID, $this->getUser()->getId());
			$c->add(MessagePeer::ID, $message_ids, Criteria::IN);
			MessagePeer::doDelete($c);
			$this->getUser()->setFlash('success', 'Your messages have been successfully deleted');
		} else {
			$message = MessagePeer::retrieveById($request->getParameter('id'));
			$this->getUser()->setFlash('error', 'You first must select a valid message.');
			
			if($message && $message->getRecipientId() == $this->getUser()->getId()) {
				$message->delete();
				$this->getUser()->setFlash('success', 'Your message has been successfully deleted');
			} else if($message) {
				$this->getUser()->setFlash('error', 'You do not have permission to delete this messsage');
			}			
		}

		$this->redirect('messages/index?group_id='.$this->group_id.'&folder='.$request->getParameter('folder', 'inbox'));
	}


	public function executeShow(sfWebRequest $request) {
		$this->message = MessagePeer::retrieveById($request->getParameter('id'));
		$this->form = new MessageForm();
		$this->forward404Unless($this->message, 'The message could not be found');
		// make sure this message belongs to that user
		if($this->message->getUserId() != $this->getUser()->getId()) {
			$this->getUser()->setFlash('error', 'You do not have permission to view this message');
			$this->redirect('messages/index?group_id='.$this->group_id);
		} else {
			$this->message->setSeen(1);
			$this->message->save();
		}
	}
}
